﻿using SuperX.Common;
using SuperX.Common.Abstract;
using SuperX.Common.BasicService;
using SuperX.Common.Log;
using SuperX.ProjectCore;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace SuperX.ProjectManager
{
    public class HostedService : SingleBase<HostedService>
    {
        public bool IsRun { get => _projectMsg.IsRun; }

        public HostedService()
        {
            _projectMsg = new ProjectMsg();
        }

        public void Start()
        {
            try
            {
                InitProject();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private void InitProject()
        {
            string projectPath = BasicServiceManager.GetStartupProject();
            //string projectPath = "Project\\Project.proj";
            if (!File.Exists(projectPath))
            {
                Common.Log.Logger.Warn("项目不存在！");
            }
            var args = Environment.GetCommandLineArgs();
            if (args.Length > 1 && args[1] != null && args[1].EndsWith(".proj"))
            {
                projectPath = args[1];
            }
            if (string.IsNullOrWhiteSpace(projectPath))
            {
                projectPath = BasicServiceManager.GetStartupProject();
            }
            var demoPath = BasicServiceManager.GetDemoProject();
            if (string.IsNullOrWhiteSpace(projectPath) && File.Exists(demoPath))
            {
                projectPath = demoPath;
            }

            if (string.IsNullOrEmpty(projectPath))
            {
                Console.WriteLine("获取项目启动路径失败，请在开发工具配置默认项目");
                SuperX.Common.Log.Logger.Warn("获取项目启动路径失败，请在开发工具配置默认项目，IoTServiceNet进程退出");
                //ProcessManager.Bash("systemctl stop IoTServiceNet");
#if !DEBUG
                IotEnvironment.LinuxCommand.SystemdStop("IoTServiceNet");
#endif
                return;
            }

            if (!File.Exists(projectPath))
            {
                Console.WriteLine("项目文件不存在，加载失败");
                SuperX.Common.Log.Logger.Warn("项目文件不存在，加载失败，IoTServiceNet进程退出");
                //ProcessManager.Bash("systemctl stop IoTServiceNet");
                IotEnvironment.LinuxCommand.SystemdStop("IoTServiceNet");
                return;
            }
            _projService = ProjService.GetInstance();
            _projService.Error += _serverHost_Error;
            _projService.LoadProject(projectPath);
            if (_projService.Project == null)
            {
                Console.WriteLine("项目加载失败");
                Common.Log.Logger.Warn("项目加载失败");
            }
            _projService.Project.Init();
            Thread.Sleep(2000);
            _projectMsg.StartProject(_projService.Project);
        }

        public static void OpenPress(string FileName, string appName)
        {
            appName = appName.ToLower().Trim();
            if (Process.GetProcesses().Where(p => p.ProcessName.ToLower().Trim() == appName).ToArray().Any())
                ClosePress(appName);
            Process pro = new Process();
            pro.StartInfo.FileName = FileName;
            pro.Start();
        }

        public static void ClosePress(string name)
        {
            name = name.ToLower().Trim();
            //获得任务管理器中的所有进程
            Process[] process = Process.GetProcesses().Where(p => p.ProcessName.ToLower().Trim() == name).ToArray();
            foreach (Process p in process)
            {
                try
                {
                    string processName = p.ProcessName.ToLower().Trim();
                    //判断是否包含阻碍更新的进程
                    if (processName == name)
                    {
                        p.Kill();
                    }
                }
                catch { }
            }
        }

        public string GetString()
        {
            return _projectMsg.GetString();
        }

        private void _serverHost_Error(object sender, ExceptionArgs e)
        {
            Console.WriteLine(e.Exception.Message);
        }

        public void Stop()
        {
            _projService.CloseProject();
        }

        private ProjService _projService;
        private ProjectMsg _projectMsg;
    }
}